// 封装axios，使用拦截器

import axios from "axios";
import { ElMessage } from "element-plus";
import useUserStore from "@/store/modules/user";

let request = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 3 * 1000,
});

request.interceptors.request.use((config) => {
  let userStore = useUserStore();
  
  if(userStore.token){
    config.headers.token = userStore.token
  }
  return config;
});
request.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    let message = "";
    //服务器挂了不会有这个结构
    let status = error.response.status;
    switch (status) {
      case 401:
        message = "TOKEN过期";
        break;
      case 403:
        message = "无权访问";
        break;
      case 500:
        message = "无权访问";
        break;
      default:
        message = "无权访问";
        break;
    }

    // 提示错误信息
    ElMessage({
        type: 'error',
        message
    });

    return Promise.reject(error)
    
  }
);

// 对外暴露
export default request;